package cn.felord.debezium.mina;

import cn.felord.debezium.service.TcpActService;
import lombok.extern.slf4j.Slf4j;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IoSession;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
@Slf4j
public class TimeServerHandler9001erw extends IoHandlerAdapter {
    @Value("${socket.port}")
    private Integer port;

    private int count = 0;
    private TcpActService tcpActService;

    public TimeServerHandler9001erw(TcpActService tcpActService) {
        this.tcpActService = tcpActService;
    }

    @Override
    public void messageReceived(IoSession session, Object message) throws IOException {
//        log.info("yyy 收到:" + message.toString());
        byte[] by = new byte[((IoBuffer)message).limit()];
        IoBuffer ioBuffer = ((IoBuffer) message).get(by);
//        StringBuffer mesbu = new StringBuffer();
        String mes = bytesToHexString(by);
//        for (int i = 0; i < by.length; i++) {
//            System.out.println(by[i]);
//            mesbu.append((char) by[i]);
//        }
//        String mes = mesbu.toString().replaceAll(" ","");

        log.info(session.getRemoteAddress() + "收到：" + mes);
//        sendMsg(session,mes);
//        session.write(mes);
//        sendMsg(session,"3030303030303030");
        tcpActService.actReceive(mes,session);
//        3030303030303030

    }
//    public static void sendMsg(IoSession session,byte[] msg) {
//        try {
//            session.write(IoBuffer.wrap(msg));
//        }catch(Exception e) {
//            System.out.println("sendMsg error: "+e.getMessage());
//            e.printStackTrace();
//        }
//    }
//    public static void sendMsg(IoSession session,String msg) {
//        System.out.println("发送:" + msg);
//        try {
//            session.write(IoBuffer.wrap(msg.getBytes()));//发送字符串
//        }catch(Exception e) {
//            System.out.println("sendMsg error: "+e.getMessage());
//            e.printStackTrace();
//        }
//    }

    /**
     * byte转hex
     * @param src
     * @return
     */
    public static String bytesToHexString(byte[] src){
        StringBuilder stringBuilder = new StringBuilder("");
         if (src == null || src.length <= 0) {
                return null;
            }
            for (int i = 0; i < src.length; i++) {
                int v = src[i] & 0xFF;
                String hv = Integer.toHexString(v);
                if (hv.length() < 2) {
                    stringBuilder.append(0);
                }
                    stringBuilder.append(hv);
                }
            return stringBuilder.toString();
        }

}

